<template>
  <div class="knowledge-base">
    <div class="header">
      <el-button :icon="ArrowLeft" @click="goBack" class="back-button">返回</el-button>
      <h2>{{ knowledgeBaseName ? knowledgeBaseName + ' - 文档管理' : '所有文档管理' }}</h2>
      <el-button type="primary" @click="showUploadDialog = true">
        <el-icon><Plus /></el-icon>
        上传文档
      </el-button>
    </div>

    <!-- 搜索功能 -->
    <div class="search-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索知识库内容..."
        class="search-input"
        @keyup.enter="searchKnowledge"
      >
        <template #append>
          <el-button @click="searchKnowledge" :disabled="!searchQuery.trim()">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      <el-button 
        v-if="searchQuery" 
        @click="clearSearch" 
        type="info" 
        size="small"
        style="margin-left: 10px;"
      >
        <el-icon><Close /></el-icon>
        清空
      </el-button>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchResults.length > 0" class="search-results">
      <h3>搜索结果</h3>
      <div class="result-list">
        <el-card v-for="(result, index) in searchResults" :key="index" class="result-item">
          <div class="result-content">
            <div class="result-text">{{ result.content }}</div>
            <div class="result-meta">
              <span class="similarity">相似度: {{ (result.similarity * 100).toFixed(1) }}%</span>
              <span class="source">来源: {{ result.source }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 文档列表 -->
    <div class="document-list">
      <h3>已上传文档</h3>
      <el-table :data="documents" style="width: 100%">
        <el-table-column prop="name" label="文档名称" />
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="size" label="大小" width="100">
          <template #default="scope">
            {{ formatFileSize(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.uploadTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="showDocumentPreview(scope.row)">预览</el-button>
            <el-button size="small" type="danger" @click="deleteDocument(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 上传对话框 -->
    <el-dialog v-model="showUploadDialog" title="上传文档" width="500px">
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :file-list="fileList"
        multiple
        drag
        accept=".txt,.md,.pdf,.doc,.docx"
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 txt、md、pdf、doc、docx 格式，单个文件不超过 10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUpload">取消</el-button>
          <el-button type="primary" @click="uploadFiles" :loading="uploading">
            上传
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文档预览对话框 -->
    <el-dialog v-model="showPreviewDialog" title="文档预览" width="800px">
      <div class="preview-content">
        <h4>{{ previewDocument.name }}</h4>
        <div class="preview-text">{{ previewDocument.content }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, UploadFilled, Close, ArrowLeft } from '@element-plus/icons-vue'
import api from '@/utils/api'

const route = useRoute()
const router = useRouter()

// 响应式数据
const searchQuery = ref('')
const searchResults = ref([])
const documents = ref([])
const fileList = ref([])
const showUploadDialog = ref(false)
const showPreviewDialog = ref(false)
const uploading = ref(false)
const previewDocument = ref({})
const uploadRef = ref(null)
const knowledgeBaseName = ref('')

// 从路由获取 knowledgeBaseId
const knowledgeBaseId = ref(route.params.knowledgeBaseId || null)

// 加载文档列表
const loadDocuments = async () => {
  try {
    let response;
    if (knowledgeBaseId.value) {
      response = await api.get(`/api/knowledge/documents?knowledgeBaseId=${knowledgeBaseId.value}`)
    } else {
      response = await api.get('/api/knowledge/documents')
    }
    documents.value = response.data
  } catch (error) {
    console.error('加载文档列表失败:', error)
    ElMessage.error('加载文档列表失败')
  }
}

// 获取知识库名称
const fetchKnowledgeBaseName = async (id) => {
  try {
    const response = await api.get(`/api/knowledge/bases/${id}`)
    knowledgeBaseName.value = response.data.name
  } catch (error) {
    console.error('获取知识库名称失败:', error)
    knowledgeBaseName.value = '未知知识库'
  }
}

// 监听 knowledgeBaseId 变化，重新加载数据
watch(knowledgeBaseId, (newId) => {
  console.log('knowledgeBaseId changed:', newId)
  loadDocuments()
  if (newId) {
    fetchKnowledgeBaseName(newId)
  }
}, { immediate: true })

// 搜索知识库
const searchKnowledge = async () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning('请输入搜索内容')
    return
  }

  try {
    console.log('开始搜索，查询内容:', searchQuery.value)
    
    const response = await api.get('/api/knowledge/search', {
      params: {
        query: searchQuery.value,
        maxResults: 10,
        minScore: 0.8
      }
    })
    
    console.log('搜索结果:', response.data)
    searchResults.value = response.data
    
    if (response.data.length === 0) {
      ElMessage.info('未找到相关结果')
    } else {
      ElMessage.success(`找到 ${response.data.length} 条相关结果`)
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败: ' + (error.response?.data?.message || error.message))
  }
}

// 清空搜索
const clearSearch = () => {
  searchQuery.value = ''
  searchResults.value = []
  ElMessage.info('搜索内容已清空')
}

// 处理文件选择
const handleFileChange = (file, uploadFileList) => {
  console.log('选择的文件:', file)
  console.log('上传文件列表:', uploadFileList)
  
  // 验证文件类型
  const allowedTypes = ['.txt', '.md', '.pdf', '.doc', '.docx']
  const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
  
  if (!allowedTypes.includes(fileExtension)) {
    ElMessage.error(`不支持的文件格式: ${fileExtension}`)
    return false
  }
  
  // 验证文件大小 (10MB)
  const maxSize = 10 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error(`文件大小不能超过 10MB`)
    return false
  }
  fileList.value = uploadFileList // 更新文件列表
}

// 处理文件移除
const handleFileRemove = (file, uploadFileList) => {
  fileList.value = uploadFileList // 更新文件列表
}

// 取消上传
const cancelUpload = () => {
  showUploadDialog.value = false
  uploadRef.value.clearFiles() // 清空文件列表
  fileList.value = []
}

// 上传文件
const uploadFiles = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  uploading.value = true
  const formData = new FormData()
  fileList.value.forEach(file => {
    formData.append('file', file.raw)
  })
  
  if (knowledgeBaseId.value) {
    formData.append('knowledgeBaseId', knowledgeBaseId.value);
  }

  try {
    await api.post('/api/knowledge/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    ElMessage.success('文档上传成功，正在处理中...')
    cancelUpload()
    loadDocuments() // 刷新文档列表
  } catch (error) {
    console.error('文档上传失败:', error)
    ElMessage.error('文档上传失败: ' + (error.response?.data?.message || error.message))
  } finally {
    uploading.value = false
  }
}

// 显示文档预览
const showDocumentPreview = (document) => {
  previewDocument.value = document
  showPreviewDialog.value = true
}

// 删除文档
const deleteDocument = async (document) => {
  ElMessageBox.confirm(
    `此操作将永久删除文档 "${document.name}"，是否继续？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await api.delete(`/api/knowledge/documents/${document.id}`)
        ElMessage.success('文档删除成功！')
        loadDocuments() // 刷新文档列表
      } catch (error) {
        console.error('删除文档失败:', error)
        ElMessage.error('删除文档失败: ' + (error.response?.data?.message || error.message))
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-'
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

// 获取文档状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'processing': return 'info'
    case 'processed': return 'success'
    case 'failed': return 'danger'
    default: return ''
  }
}

// 获取文档状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'processing': return '处理中'
    case 'processed': return '已处理'
    case 'failed': return '处理失败'
    default: return status
  }
}

// 返回上级页面
const goBack = () => {
  router.push({ name: 'KnowledgeBaseManagement' });
};
</script>

<style scoped>
.knowledge-base {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #f5f7fa;
  overflow: auto;
  box-sizing: border-box;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  max-width: 500px;
}

.search-results {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background-color: #f4f4f5;
}

.search-results h3 {
  margin-top: 0;
  color: #606266;
  font-size: 16px;
  margin-bottom: 10px;
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.result-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.result-content {
  font-size: 14px;
  color: #303133;
}

.result-meta {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  display: flex;
  justify-content: space-between;
}

.similarity {
  color: #409eff;
}

.source {
  color: #67c23a;
}

.document-list h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #606266;
}

/* 确保表格高度正确并可滚动 */
.document-list .el-table {
  flex: 1;
  overflow-y: auto;
  max-height: 60vh;
}

/* 上传对话框 */
:deep(.el-upload-dragger) {
  padding: 30px;
}

:deep(.el-upload__text) {
  font-size: 16px;
}

:deep(.el-upload__tip) {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.preview-content {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  padding: 15px;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.preview-content h4 {
  margin-top: 0;
  color: #303133;
  font-size: 18px;
  margin-bottom: 10px;
}

.preview-text {
  white-space: pre-wrap;
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
}
</style> 